package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.DeptDto;
import cn.livingCloud.dto.ReportRuleFormDto;
import cn.livingCloud.entity.core.Dept;
import cn.livingCloud.entity.core.ReportRule;
import cn.livingCloud.repository.DeptMapper;
import cn.livingCloud.repository.ReportRuleMapper;
import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * Created by DingJie on 2016/6/29.
 */
public class ReportRuleFormDtoLoader {
    protected transient DeptMapper deptMapper = BeanProvider.getBean(DeptMapper.class);
    protected transient ReportRuleMapper reportRuleMapper = BeanProvider.getBean(ReportRuleMapper.class);
    private ReportRuleFormDto formDto;

    public ReportRuleFormDtoLoader(ReportRuleFormDto formDto) {
        this.formDto = formDto;
    }

    public void loadFormDto() {
        loadAllDept();
        if (!StringUtils.isEmpty(formDto.getUuid())) {
            loadReportRuleDto();
        }
    }

    private void loadAllDept() {
        List<Dept> allDept = deptMapper.getAllList();
        //拿到第一级
        List<DeptDto> first = formDto.getChildDept();
        for (Dept dept : allDept) {
            if (StringUtils.isEmpty(dept.getParentUuid())) {
                first.add(new DeptDto(dept));
            }
        }
        getChild(first, allDept);
    }

    /**
     * 获取子级
     *
     * @param parent  上级部门
     * @param allDept 所有的部门
     */
    private void getChild(List<DeptDto> parent, List<Dept> allDept) {
        for (DeptDto deptDto : parent) {
            for (Dept dept : allDept) {
                if (deptDto.getUuid().equals(dept.getParentUuid())) {
                    deptDto.getChildDept().add(new DeptDto(dept));
                }
            }
            getChild(deptDto.getChildDept(), allDept);
        }
    }

    public void loadReportRuleDto() {
        ReportRule reportRule = reportRuleMapper.selectByPrimaryKey(formDto.getUuid());
        formDto.loadReportRule(reportRule);
    }
}
